import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import { App } from "vue";
import { createRouterGuard } from "@/router/guard";

/**
 * @description 自动化引入(方法globEager已弃用).
 */
const modules: any = import.meta.glob("./modules/**/*.ts", {
  eager: true,
});

const routeModuleList: RouteRecordRaw[] = [];

Object.keys(modules).forEach((key) => {
  const mod = modules[key].default || {};
  const modList = Array.isArray(mod) ? [...mod] : [mod];
  routeModuleList.push(...modList);
});

const baseRoutes: Array<RouteRecordRaw> = [
  {
    name: "SignIn",
    path: "/sign-in",
    component: () => import("@/views/system-view/sign-in/SignIn.vue"),
    meta: {
      title: "登录",
    },
  },
  {
    name: "BaseTemplate",
    path: "/",
    component: () => import("@/layouts/VTemplate.vue"),
  },
  {
    name: "TestPage",
    path: "/test",
    component: () => import("@/views/TestPage.vue"),
    meta: {
      title: "登录",
    },
  },
];

export const constantRoutes = baseRoutes;

/**
 * 菜单排序
 */
function sortRoute(a: any, b: any) {
  return (a.meta?.sort || 0) - (b.meta?.sort || 0);
}

routeModuleList.sort(sortRoute);

// 定义路由
const router = createRouter({
  history: createWebHashHistory(),
  routes: baseRoutes.concat(routeModuleList),
  strict: true,
});

/**
 * @description 挂载路由
 */
export async function setupRouter(app: App) {
  app.use(router);

  // 路由拦截
  createRouterGuard(router);

  // 路由准备就绪后，才挂载APP实例
  await router.isReady();
}

export default router;
